import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      // component: HomeView,
      redirect: '/login'
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/homepage',
      component: () => import('../views/HomePage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/chart',
      component: () => import('../views/ChartPage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/table',
      component: () => import('../views/TablePage.vue'),
      meta: { requiresAuth: true }
    } // 添加新的路由
  ]
})
router.beforeEach((to, from, next) => {
  const loggedIn = localStorage.getItem('user')
  if (
    to.matched.some((record) => {
      return record.meta.requiresAuth
    }) &&
    !loggedIn
  ) {
    next('/')
  } else {
    next()
  }
})
export default router
